package com.gankao.cursortest.ui.provider

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.core.content.FileProvider
import java.io.File

/**
 * @author shuguo
 * @date :2024/11/16 11:19
 * @description:
 */
object GkFileProvider {

    /**
     * 分享单个文件
     * @param context 上下文
     * @param targetPackageName 目标应用包名
     * @param file 要分享的文件
     */
    fun shareFile(context: Context, targetPackageName: String, file:File){
        Log.e("GkFileProvider","shareFile targetPackageName:$targetPackageName, file:${file.absolutePath}")
        // 生成文件 URI
        val fileUri = FileProvider.getUriForFile(
            context,
            "${context.packageName}.fileprovider",
            file
        )

        // 授予临时访问权限
        context.grantUriPermission(
            targetPackageName,  // 接收数据的应用包名
            fileUri,
            Intent.FLAG_GRANT_READ_URI_PERMISSION// or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
        )
    }

    /**
     * 分享整个目录
     * @param context 上下文
     * @param targetPackageName 目标应用包名
     * @param dataDir 要分享的目录
     */
    fun shareDirectory(context: Context, targetPackageName: String, dataDir:File?) {

        Log.e("GkFileProvider","shareDirectory targetPackageName:$targetPackageName, dataDir:${dataDir?.absolutePath}")

        val list = mutableListOf<Uri>()

        // 递归遍历目录下的所有文件
        fun shareFilesInDirectory(directory: File) {
            directory.listFiles()?.forEach { file ->
                if (file.isFile) {
                    // 为每个文件生成 URI 并授权
                    val fileUri = FileProvider.getUriForFile(
                        context,
                        "${context.packageName}.fileprovider",
                        file
                    )

                    context.grantUriPermission(
                        targetPackageName,
                        fileUri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION// or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    )

                    list.add(fileUri)

                    Log.e("GkFileProvider","shareDirectory fileUri:$fileUri")
                } else if (file.isDirectory) {
                    // 如果是目录，递归处理
                    shareFilesInDirectory(file)
                }
            }
        }

        // 开始共享整个目录
        dataDir?.let { shareFilesInDirectory(it) }

        Log.e("GkFileProvider","shareDirectory completed, size:${list.size}")
    }

}